package mall.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import mall.pojo.Category;
import mall.pojo.Shop;
import mall.service.CategoryService;
import mall.service.ShopService;
import mall.util.UtilityClass;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class CategoryController {
	@Autowired
	private CategoryService categoryService;
	
	@Autowired
	private ShopService shopService;
	
	// create new blance object
	@RequestMapping(value="/manage-shop-cat", method=RequestMethod.GET)
	public ModelAndView category(Map<String, Object> map,HttpSession session){
		int shopId=(Integer)session.getAttribute("shopId");
		List<Category> listCategory=categoryService.getCategoryShop(shopId);
		map.put("listCategory", listCategory);
		return new ModelAndView(UtilityClass.VIEW_SHOP_CATEGORY_ADMIN, "category", new Category());
	}
	@RequestMapping(value="/manage-shop-cat", method=RequestMethod.POST)
	public ModelAndView addCategory(@ModelAttribute("category") Category category,
			BindingResult bindingResult,HttpSession session,Map<String, Object> map){
		int shopId=Integer.parseInt(session.getAttribute("shopId").toString());
		Shop shop=shopService.getShop(shopId);
		category.setShop(shop);
		categoryService.createCategory(category);
		List<Category> listCategory=categoryService.getCategoryShop(shopId);
		map.put("listCategory", listCategory);
		return new ModelAndView(UtilityClass.VIEW_SHOP_CATEGORY_ADMIN, "category", new Category());
	} 
	
	@RequestMapping(value="/updatecategory",method= RequestMethod.GET)
	public ModelAndView editCategory(@ModelAttribute("id") int catId){
		ModelAndView modelAndView = new ModelAndView();
		Category category =categoryService.getCategory(catId);
		modelAndView.addObject("category", category);
		modelAndView.setViewName(UtilityClass.VIEW_SHOP_UPDATE_CATEGORY_ADMIN);
		return modelAndView;
	}
	
	@RequestMapping(value="/updatecategory",method= RequestMethod.POST)
	public ModelAndView updateCategory(@ModelAttribute("category") Category category,
			BindingResult bindingResult,HttpSession session){
		ModelAndView modelAndView=new ModelAndView();
		int shopId=(Integer)session.getAttribute("shopId");
		categoryService.updateCategory(category);
		List<Category> listCategory=categoryService.getCategoryShop(shopId);
		modelAndView.addObject("listCategory", listCategory);
		modelAndView.addObject("category", new Category());
		modelAndView.setViewName(UtilityClass.VIEW_SHOP_CATEGORY_ADMIN);
		return modelAndView;
	}
	
	
	
}
